import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  runApp(const DialogExampleApp());
}

class DialogExampleApp extends StatelessWidget {
  const DialogExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter对话框示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
      ),
      home: const DialogTestRoute(),
    );
  }
}

class DialogTestRoute extends StatefulWidget {
  const DialogTestRoute({super.key});

  @override
  State<DialogTestRoute> createState() => _DialogTestRouteState();
}

class _DialogTestRouteState extends State<DialogTestRoute> {
  bool _withTree = false; // 复选框选中状态

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("对话框示例"),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "基础对话框",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              children: [
                ElevatedButton(
                  onPressed: () => _showAlertDialog1(context),
                  child: const Text("AlertDialog"),
                ),
                ElevatedButton(
                  onPressed: () => _showAlertDialog2(context),
                  child: const Text("带复选框的对话框"),
                ),
                ElevatedButton(
                  onPressed: () => _showSimpleDialog(context),
                  child: const Text("SimpleDialog"),
                ),
                ElevatedButton(
                  onPressed: () => _showAboutDialog(context),
                  child: const Text("AboutDialog"),
                ),
              ],
            ),
            const SizedBox(height: 30),
            const Text(
              "其他类型对话框",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              children: [
                ElevatedButton(
                  onPressed: () => _showModalBottomSheet(context),
                  child: const Text("底部菜单列表"),
                ),
                ElevatedButton(
                  onPressed: () => _showLoadingDialog(context),
                  child: const Text("Loading对话框"),
                ),
                ElevatedButton(
                  onPressed: () => _showCustomLoadingDialog(context),
                  child: const Text("自定义Loading"),
                ),
                ElevatedButton(
                  onPressed: () => _showDatePicker1(context),
                  child: const Text("Material日期选择器"),
                ),
                ElevatedButton(
                  onPressed: () => _showDatePicker2(context),
                  child: const Text("iOS日期选择器"),
                ),
              ],
            ),
            const SizedBox(height: 30),
            const Text(
              "对话框动画和状态管理",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Wrap(
              spacing: 10,
              children: [
                ElevatedButton(
                  onPressed: () => _showAnimatedDialog(context),
                  child: const Text("动画对话框"),
                ),
                ElevatedButton(
                  onPressed: () => _showStatefulDialog(context),
                  child: const Text("状态管理对话框"),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 1. 基础AlertDialog
  Future<bool?> _showAlertDialog1(BuildContext context) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text("提示"),
          content: const Text("您确定要删除当前文件吗?"),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                // 关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
              child: const Text("删除"),
            ),
          ],
        );
      },
    );
  }

  // 2. 带复选框的AlertDialog
  Future<bool?> _showAlertDialog2(BuildContext context) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text("提示"),
          content: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const Text("您确定要删除当前文件吗?"),
              Row(
                children: <Widget>[
                  // 通过Builder来获得构建Checkbox的`context`，
                  // 这是一种常用的缩小`context`范围的方式
                  Builder(
                    builder: (BuildContext context) {
                      return Checkbox(
                        value: _withTree,
                        onChanged: (bool? value) {
                          (context as Element).markNeedsBuild();
                          setState(() {
                            _withTree = value ?? false;
                          });
                        },
                      );
                    },
                  ),
                  const Text("同时删除子目录？"),
                ],
              ),
            ],
          ),
          actions: <Widget>[
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text("取消"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              child: const Text("删除"),
            ),
          ],
        );
      },
    );
  }

  // 3. SimpleDialog
  Future<String?> _showSimpleDialog(BuildContext context) {
    return showDialog<String>(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: const Text("请选择语言"),
          children: <Widget>[
            SimpleDialogOption(
              onPressed: () => Navigator.of(context).pop("中文简体"),
              child: const Padding(
                padding: EdgeInsets.symmetric(vertical: 6),
                child: Text('中文简体'),
              ),
            ),
            SimpleDialogOption(
              onPressed: () => Navigator.of(context).pop("English"),
              child: const Padding(
                padding: EdgeInsets.symmetric(vertical: 6),
                child: Text('English'),
              ),
            ),
          ],
        );
      },
    );
  }

  // 4. AboutDialog
  void _showAboutDialog(BuildContext context) {
    showAboutDialog(
      context: context,
      applicationName: "Flutter对话框示例",
      applicationVersion: "1.0.0",
      applicationIcon: const FlutterLogo(size: 50),
      children: <Widget>[const Text("这是一个Flutter对话框示例应用，展示了各种对话框的使用方法。")],
    );
  }

  // 5. 底部菜单列表
  Future<int?> _showModalBottomSheet(BuildContext context) {
    return showModalBottomSheet<int>(
      context: context,
      builder: (BuildContext context) {
        return ListView.builder(
          itemCount: 30,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: Text("选项 $index"),
              onTap: () => Navigator.of(context).pop(index),
            );
          },
        );
      },
    );
  }

  // 6. Loading对话框
  void _showLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false, // 点击遮罩不关闭对话框
      builder: (context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: const <Widget>[
              CircularProgressIndicator(),
              Padding(
                padding: EdgeInsets.only(top: 26.0),
                child: Text("正在加载，请稍后..."),
              ),
            ],
          ),
        );
      },
    );
  }

  // 7. 自定义Loading对话框
  void _showCustomLoadingDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return UnconstrainedBox(
          constrainedAxis: Axis.vertical,
          child: SizedBox(
            width: 280,
            child: AlertDialog(
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: const <Widget>[
                  CircularProgressIndicator(value: .8),
                  Padding(
                    padding: EdgeInsets.only(top: 26.0),
                    child: Text("正在加载，请稍后..."),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // 8. Material日期选择器
  Future<DateTime?> _showDatePicker1(BuildContext context) {
    var date = DateTime.now();
    return showDatePicker(
      context: context,
      initialDate: date,
      firstDate: date,
      lastDate: date.add(const Duration(days: 30)),
    );
  }

  // 9. iOS日期选择器
  Future<DateTime?> _showDatePicker2(BuildContext context) {
    var date = DateTime.now();
    return showCupertinoModalPopup(
      context: context,
      builder: (ctx) {
        return SizedBox(
          height: 200,
          child: CupertinoDatePicker(
            mode: CupertinoDatePickerMode.dateAndTime,
            minimumDate: date,
            maximumDate: date.add(const Duration(days: 30)),
            maximumYear: date.year + 1,
            onDateTimeChanged: (DateTime value) {
              debugPrint(value.toString());
            },
          ),
        );
      },
    );
  }

  // 10. 动画对话框
  void _showAnimatedDialog(BuildContext context) {
    showGeneralDialog(
      context: context,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return FadeTransition(
          opacity: animation,
          child: ScaleTransition(
            scale: animation,
            child: AlertDialog(
              title: const Text("动画对话框"),
              content: const Text("这是一个带有淡入和缩放动画的对话框"),
              actions: <Widget>[
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text("确定"),
                ),
              ],
            ),
          ),
        );
      },
      barrierDismissible: true,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black54,
      transitionDuration: const Duration(milliseconds: 300),
    );
  }

  // 11. 状态管理对话框
  void _showStatefulDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return _StatefulDialog();
      },
    );
  }
}

// 状态管理对话框组件
class _StatefulDialog extends StatefulWidget {
  @override
  _StatefulDialogState createState() => _StatefulDialogState();
}

class _StatefulDialogState extends State<_StatefulDialog> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text("状态管理对话框"),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("计数器: $_counter"),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    _counter++;
                  });
                },
                child: const Text("+"),
              ),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    _counter--;
                  });
                },
                child: const Text("-"),
              ),
            ],
          ),
        ],
      ),
      actions: <Widget>[
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text("关闭"),
        ),
      ],
    );
  }
}
